package com.example.service;

import java.util.concurrent.TimeUnit;

import com.example.constant.ErrorMessageConstant;
import com.example.constant.MessageTypeConstant;
import com.example.entity.Attachment;
import com.example.entity.ChargingPile;
import com.example.entity.body.impl.ASDUBody;
import com.example.entity.factory.Unpooled;
import com.example.entity.message.Message;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;

public class TimeSynHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
		Message message = (Message) msg;

		ASDUBody body = message.getBody();
		Byte type = body.getType();
		ChargingPile state = (ChargingPile) ctx.channel().attr(AttributeKey.valueOf("state")).get();

		if (type == MessageTypeConstant.TIME_SYN_MESSAGE) {
			if (state.isCountEnd()) {
				System.out.println("时间同步接受");
				String[] times = { "年", "月", "日", "时", "分", "秒", "毫秒" };
				Attachment[] attachments = body.getAttachments();
				if (attachments.length == 1) {
					byte[] bs = attachments[0].getValue();
					int Mi0 = bs[0];
					int Mi1 = (bs[1] << 8);
					int Mi = Mi1 & Mi0;

					int mm = bs[2] & 0x3f;
					int HH = bs[3] & 0x1f;
					int week = bs[4] & 0xe0;// 0b 1110 0000
					int dd = bs[4] & 0x1f;// 0b 0001 1111
					int MM = bs[5] & 0x0f;
					int yy = bs[6] & 0x7f;

					System.out.println("时间解析完毕");
					System.out.printf("%d %d %d %d %d %d %d ", yy, MM, dd, week, HH, mm, Mi);
				} else {
					System.out.println("时间同步错误");
				}
				ctx.channel().eventLoop().schedule(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						
					}
				}, 10, TimeUnit.SECONDS);
				state.hasStarted();
			} else {
				// TODO 错误处理
				ctx.fireChannelRead(Unpooled.wrapperErrorMessage(ErrorMessageConstant.NO_COUNT_END));

			}

		} else {
			ctx.fireChannelRead(msg);
		}
	}
}
